package com.zjut.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zjut.domain.FinalQuestions;
import com.zjut.domain.Paper;
import com.zjut.domain.Questions;
import com.zjut.service.PaperQuestionService;
import com.zjut.service.QuestionsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/questions")
public class QuestionsController {
    @Autowired
    private QuestionsService questionsService;
    @Autowired
    private PaperQuestionService paperQuestionService;

    @PostMapping
    public Result save(@RequestBody Questions questions) {
        if (questions.getQuestion() == null || questions.getQuestion().isEmpty()
                || questions.getAnswer() == null || questions.getAnswer().isEmpty()
                || questions.getType() == null || questions.getType().isEmpty()
                || questions.getSection() == null || questions.getChapter() == null
                || questions.getDifficulty() == null) {
            return new Result(Code.SAVE_ERR, null, "请输入完整数据");
        } else if (questions.getDifficulty() > 1 || questions.getDifficulty() < 0) {
            return new Result(Code.SAVE_ERR, null, "难度系数必须在0~1之间");
        }
        boolean flag = questionsService.save(questions);
        return new Result(flag ? Code.SAVE_OK : Code.SAVE_ERR, flag);
    }

    @PutMapping
    public Result update(@RequestBody Map<String, Object> params) {

        //接收并转换参数
        ObjectMapper objectMapper = new ObjectMapper();

        Map<String, Object> questionsMap = (Map<String, Object>) params.get("formData");
        Map<String, Object> questionsMap2 = (Map<String, Object>) params.get("formData2");
        Questions newQuestions = objectMapper.convertValue(questionsMap, Questions.class);
        Questions oldQuestions = objectMapper.convertValue(questionsMap2, Questions.class);
//        System.out.println(newQuestions);
//        System.out.println(oldQuestions);
        //判空
        if (newQuestions.getQuestion() == null || newQuestions.getQuestion().isEmpty()
                || newQuestions.getAnswer() == null || newQuestions.getAnswer().isEmpty()
                || newQuestions.getType() == null || newQuestions.getType().isEmpty()
                || newQuestions.getSection() == null || newQuestions.getChapter() == null
                || newQuestions.getDifficulty() == null) {
            return new Result(Code.SAVE_ERR, null, "请输入完整数据");
        } else if (newQuestions.getDifficulty() > 1 || newQuestions.getDifficulty() < 0) {
            return new Result(Code.SAVE_ERR, null, "难度系数必须在0~1之间");
        }
        //如果题目被其它试卷引用,设置旧题目状态为false,并添加新题
        if (paperQuestionService.getByQuestionId(newQuestions.getId()) != null) {
            oldQuestions.setStatus(false);
            boolean flag1 = questionsService.update(oldQuestions);
            newQuestions.setId(null);
            boolean flag2 = questionsService.save(newQuestions);
            return new Result(flag1&&flag2 ? Code.UPDATE_OK : Code.UPDATE_ERR, flag1&&flag2);
        }
        boolean flag = questionsService.update(newQuestions);
        return new Result(flag ? Code.UPDATE_OK : Code.UPDATE_ERR, flag);
    }

    @PutMapping("delete")
    public Result delete(@RequestBody Questions questions) {
        boolean flag;
        int id = questions.getId();
        if (paperQuestionService.getByQuestionId(id) != null) {
            questions.setStatus(false);
            flag = questionsService.update(questions);
        } else {
            flag = questionsService.delete(id);
        }
        return new Result(flag ? Code.DELETE_OK : Code.DELETE_ERR, flag);
    }


    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        Questions questions = questionsService.getById(id);
        Integer code = questions != null ? Code.GET_OK : Code.GET_ERR;
        String msg = questions != null ? "" : "数据查询失败，请重试！";
        return new Result(code, questions, msg);
    }

    @GetMapping
    public Result getAll() {
        List<Questions> questionsList = questionsService.getAll();
        Integer code = questionsList != null ? Code.GET_OK : Code.GET_ERR;
        String msg = questionsList != null ? "" : "数据查询失败，请重试！";
        return new Result(code, questionsList, msg);
    }

    //试题库高级搜索、普通搜索
    @GetMapping("/{currentPage}/{pageSize}")
    public Result getPage(@PathVariable int currentPage, @PathVariable int pageSize, Questions questions,
                          @RequestParam(required = false) Double difficultyMin,
                          @RequestParam(required = false) Double difficultyMax) {

        IPage<Questions> questionsList;
        if (difficultyMin != null || difficultyMax != null) {
            if (difficultyMin == null) {
                difficultyMin = 0.0;
            } else if (difficultyMax == null) {
                difficultyMax = 1.0;
            }
            questionsList = questionsService.getPage(currentPage, pageSize, questions, difficultyMin, difficultyMax);
            if (currentPage > questionsList.getPages()) {
                questionsList = questionsService.getPage((int) questionsList.getPages(), pageSize, questions, difficultyMin, difficultyMax);
            }
        } else {
            questionsList = questionsService.getPage(currentPage, pageSize, questions);
            if (currentPage > questionsList.getPages()) {
                questionsList = questionsService.getPage((int) questionsList.getPages(), pageSize, questions);
            }
        }
        Integer code = questionsList != null ? Code.GET_OK : Code.GET_ERR;
        String msg = questionsList != null ? "" : "数据查询失败，请重试！";
        return new Result(code, questionsList, msg);
    }
}
